import React from 'react';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { ChevronLeft, ChevronRight, X } from 'lucide-react';

interface MonthPickerProps {
  selectedDate: Date;
  onSelect: (date: Date) => void;
  onClose: () => void;
}

export default function MonthPicker({ selectedDate, onSelect, onClose }: MonthPickerProps) {
  const [currentYear, setCurrentYear] = React.useState(selectedDate.getFullYear());
  const months = Array.from({ length: 12 }, (_, i) => new Date(currentYear, i));

  const handlePrevYear = () => {
    setCurrentYear(year => year - 1);
  };

  const handleNextYear = () => {
    setCurrentYear(year => year + 1);
  };

  return (
    <div className='fixed inset-0 bg-black/50 z-50 flex items-end justify-center animate-in slide-in-from-bottom'>
      <div className='bg-white w-full rounded-t-2xl max-h-[80vh] overflow-auto'>
        <div className='sticky top-0 bg-white border-b'>
          <div className='flex items-center justify-between p-4'>
            <h3 className='text-lg font-semibold'>选择月份</h3>
            <button onClick={onClose} className='p-1'>
              <X className='w-6 h-6 text-gray-500' />
            </button>
          </div>

          <div className='flex items-center justify-between px-4 pb-4'>
            <button
              onClick={handlePrevYear}
              className='p-2 hover:bg-gray-100 rounded-lg'
            >
              <ChevronLeft className='w-5 h-5' />
            </button>
            <span className='text-lg font-medium'>{currentYear}年</span>
            <button
              onClick={handleNextYear}
              className='p-2 hover:bg-gray-100 rounded-lg'
            >
              <ChevronRight className='w-5 h-5' />
            </button>
          </div>
        </div>

        <div className='grid grid-cols-3 gap-4 p-4'>
          {months.map((month) => {
            const isSelected =
              selectedDate.getMonth() === month.getMonth() &&
              selectedDate.getFullYear() === month.getFullYear();

            return (
              <button
                key={month.getTime()}
                onClick={() => {
                  onSelect(month);
                  onClose();
                }}
                className={`
                  p-4 rounded-xl text-center transition-all
                  ${isSelected
                    ? 'bg-blue-500 text-white shadow-lg scale-105'
                    : 'bg-gray-50 text-gray-700 hover:bg-gray-100'
                  }
                `}
              >
                <span className='text-lg font-medium'>
                  {format(month, 'M', { locale: zhCN })}月
                </span>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}
